# -*- coding: UTF-8 -*- #

from Base import BaseHandler
import hashlib
import json
from FormValidate import Validate
import time
from tornado.locale import Locale

class Avt( BaseHandler ):
    def get( self ):
        mode = self.get_argument( "mode", None )
        if mode and mode == 'exit':
            self.session['user_id'] = None
            self.clear_all_cookies()
            return self.redirect( '%s'%(self.get_argument("uri","/")) )
        if self.is_avt():
            return self.redirect( '/' )
        values = dict( 
            post = False,
            redirect_to = self.get_argument("uri","/"),
            paging = None,
        )
        self.Render( 'avt.html', **values )
        return

    def post( self ):
        name = self.get_argument( "user", None )
        passwd = self.get_argument( "passwd", None )
        if not name or not passwd:
            self.redirect( '/avt?err=1' )
            return
        passwd = hashlib.md5( passwd ).hexdigest()
        user = self.db.users.find_one( {'login':name} )
        if not user:
            self.redirect( '/avt?err=1' )
            return
        if passwd != user['user_password']:
            self.redirect( '/avt?err=1' )
        self.session['user_id'] = user['login']
        self.redirect( '%s'%(self.get_argument("uri","/")) )
        return
        values = dict( 
            post = True,
            name = name,
            passwd = passwd,
            user_p = user,
            paging = None,
        )
        self.Render( 'avt.html', **values )


class Regisration( BaseHandler ):
    def get( self ):
        if self.is_avt():
            return self.redirect( '/' )
        values = dict(
            xsrf_token = self.xsrf_token,
            post = False,
            paging = None,
        )
        self.Render( 'registration.html', **values )
        return

    def post( self ):
        jsonData = self.get_argument( 'jsonData', None )
        if jsonData:
            data = json.loads( jsonData )
            validate = Validate()
            error = ""
            #email
            if validate.email( data['mail'] ):
                mail = True
            else:
                mail = False
                error = "%s - %s\n" % ( error, self.locale.translate("Check your Email") )
            #login
            if validate.login( data['login'] ):
                login = True
            else:
                login = False
                error = "%s - %s\n" % ( error, self.locale.translate("Field login must contain between 4 and 12 characters and only letters") )
            #passwd
            if validate.passwd( data['pass'] ):
                passwd = True
            else:
                passwd = False
                error = "%s - %s\n" % ( error, self.locale.translate("The field of the password must contain between 6 and 12 characters and only letters and numbers") )
            #repasswd
            if data['pass'] == data['repass']:
                passwd2 = True
            else:
                passwd2 = False
                error = "%s - %s\n" % ( error, self.locale.translate("Passwords do not match") )
            #captcha
            if data['captcha'] == self.get_session( 'captcha' ):
                captcha = True
            else:
                captcha = False
                error = "%s - %s\n" % ( error, self.locale.translate("Make sure you enter characters from the image") )
            if login:
                logindb = self.db.users.find_one( {'login':data['login']} )
                if logindb:
                    login = False
                    error = "%s - %s\n" % ( error, self.locale.translate("Username already exists") )
            if mail:
                maildb = self.db.users.find_one( {'user_email':data['mail']} )
                if maildb:
                    mail = False
                    error = "%s - %s\n" % ( error, self.locale.translate("E-mail is already bound to one of the users") )
            #print error

            if login and mail and passwd and passwd2 and captcha:
                error = self.lang.reg_is_ok
                reg = True
                self.db.users.insert( {
                                      'login':data['login'],
                                      'user_email':data['mail'],
                                      'user_password':hashlib.md5( data['pass'] ).hexdigest(),
                                      'user_date_register':time.strftime( "%Y-%m-%d %H:%M:%S" ),
                                      'user_ip_register':self.request.remote_ip
                                      } )
            else:
                reg = False

            ck_pass = passwd
            ck_login = login
            ck_mail = mail
            ck_captcha = captcha
            ck_pass2 = passwd2
            ck_data = {
                'ck_login':ck_login,
                'ck_mail':ck_mail,
                'ck_pass':ck_pass,
                'ck_pass2':ck_pass2,
                'ck_captcha':ck_captcha,
                'error':error,
                'reg':reg,
                }
            data.update( ck_data )
        else:
            data = 'None'
        s = json.dumps( data )
        #print(s)
        return self.write( s )
        self.redirect( '/registration' )
